package com.medical.app.service.impl;

import com.medical.app.entity.MedicalRecord;
import com.medical.app.repository.MedicalRecordRepository;
import com.medical.app.service.MedicalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {

    @Autowired
    private MedicalRecordRepository medicalRecordRepository;

    @Override
    public List<MedicalRecord> getUserRecords(Long userId) {
        return medicalRecordRepository.findByUserIdOrderByDateDesc(userId);
    }

    @Override
    public MedicalRecord saveRecord(MedicalRecord record) {
        return medicalRecordRepository.save(record);
    }

    @Override
    public MedicalRecord updateRecord(Long id, MedicalRecord record) {
        Optional<MedicalRecord> existingRecord = medicalRecordRepository.findById(id);
        if (existingRecord.isPresent()) {
            MedicalRecord recordToUpdate = existingRecord.get();
            // 更新所有字段
            recordToUpdate.setDate(record.getDate());
            recordToUpdate.setHospital(record.getHospital());
            recordToUpdate.setDepartment(record.getDepartment());
            recordToUpdate.setDoctor(record.getDoctor());
            recordToUpdate.setDiagnosis(record.getDiagnosis());
            recordToUpdate.setSymptoms(record.getSymptoms());
            recordToUpdate.setPrescription(record.getPrescription());
            recordToUpdate.setImageUrls(record.getImageUrls());
            return medicalRecordRepository.save(recordToUpdate);
        } else {
            throw new RuntimeException("病例记录不存在");
        }
    }

    @Override
    public void deleteRecord(Long id) {
        medicalRecordRepository.deleteById(id);
    }

    @Override
    public Optional<MedicalRecord> findById(Long id) {
        return medicalRecordRepository.findById(id);
    }

    @Override
    public long getRecordCount(Long userId) {
        return medicalRecordRepository.countByUserId(userId);
    }
}